package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.TextViewUtils;
import com.dindang.propertyfee.mvp.contract.PaymentDetailsContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.PaymentDetailViewAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class PaymentDetailsPresenter extends BasePresenter<PaymentDetailsContract.Model, PaymentDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private PaymentDetailViewAdapter mAdapter;
    private List<PropertyCharge.RecordDetail> mRecordDetailList = new ArrayList<>();
    private boolean isDetailVisibility = true;
    private PropertyCharge.RecordDetailParam mParam = new PropertyCharge.RecordDetailParam();
    private PropertyCharge.RecordDetail mRecordDetail;

    private String[] mCollectionType = {"", "现金", "POS", "微信", "支付宝", "银行转账"};


    private int interval;
    private ProgressDialog progressDialog;
    private final static int MAX_LEFT_DISTANCE = 255;
    private boolean isCircle = false;


    public void onStop() {
        if (progressDialog != null && !mRootView.getActivity().isFinishing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        isCircle = false;

//        mRootView.getActivity().unregisterReceiver(printReceive);
//        if(mRootView.getUsbThermalPrinter() != null && haveUsbPrint){
//            mRootView.getUsbThermalPrinter().stop();
//        }
    }


    String[] portNum = new String[20];
    String[] productNum = new String[20];
    String[] readerNum = new String[4];

    @Inject
    public PaymentDetailsPresenter(PaymentDetailsContract.Model model, PaymentDetailsContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mParam.id = mRootView.getActivity().getIntent().getStringExtra(AppConst.ID);
        initView();
        //真数据
        queryRecordDetail();
        initListener();
    }

    private SharedPreferences preference;
    private SharedPreferences.Editor editor;

    private void initView() {
        mAdapter = new PaymentDetailViewAdapter(mRecordDetailList, new PaymentDetailViewAdapter.OnPaymentDetailListener() {
            @Override
            public void onClick(int mPosition) {
            }
        });
        mRootView.getListview().setAdapter(mAdapter);
        mRootView.getListview().setNestedScrollingEnabled(false);
        mRootView.getListview().setFocusable(false);
    }

    private void initListener() {
        mRootView.getTvCommit().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转打印
                ARouter.getInstance().build("/propertyfee/activity/PrintActivity")
                .withString(AppConst.ID, mParam.id)
                        .navigation();
            }
        });
    }

    /**
     * 获取数据
     */
    public void queryRecordDetail() {
        mModel.queryRecordDetail(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(dismPosable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 DismPosable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.RecordDetail>>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<List<PropertyCharge.RecordDetail>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }

                mRecordDetailList.addAll(response.getData());

                if (null != mRecordDetailList && mRecordDetailList.size() > 0) {
                    PropertyCharge.RecordDetail recordDetail = mRecordDetailList.get(0);
                    setData(recordDetail);
                    mAdapter.setIsDetailVisibility(isDetailVisibility);
                    mAdapter.notifyDataSetChanged();
                }

            }
        });
    }

    /**
     * 设置数据
     * @param recordDetail
     */
    private void setData(PropertyCharge.RecordDetail recordDetail){
        this.mRecordDetail = recordDetail;
        mRootView.getTvTotalPrice().setText(TextViewUtils.getPaymentDetailsPrice(recordDetail.c_paid_amount));
        mRootView.getTvNumber().setText(recordDetail.c_payment_no);
        mRootView.getTvData().setText(recordDetail.d_receipt_date);
        mRootView.getTvAddress().setText(recordDetail.addr);
        mRootView.getTvName().setText(recordDetail.c_payment_name);
        mRootView.getTvPayPeople().setText(recordDetail.c_payee_name);
        mRootView.getTvPayType().setText(mCollectionType[recordDetail.c_collection_type]);
        mRootView.getTvTotalPrice2().setText(TextViewUtils.getPaymentDetailsPrice2(recordDetail.c_paid_amount));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mParam = null;
        this.mRecordDetailList = null;
        this.mAdapter = null;
        this.mCollectionType = null;
        this.mRecordDetail = null;
    }

    public void finish(){
        if(isDetailVisibility){
            mRootView.getActivity().finish();
        }else{
            isDetailVisibility = true;
            mAdapter.setIsDetailVisibility(isDetailVisibility);
            mAdapter.notifyDataSetChanged();
            mRootView.getTvTitle().setText("收款详情");
            mRootView.getTvCommit().setText("打印");
        }
    }

    public String getString(int string){
        return ArmsUtils.getString(mApplication, string);
    }

}
